<template>
  <div class="mt-1">
    <van-form>
      <h4 style="margin: 0 0 0.4rem 1rem; color: gray">
        当前产区:{{ this.$store.getters.productionLine }}
      </h4>
      <van-field
        readonly
        clickable
        name="picker"
        :value="selectedQuantity.MoveTypeName"
        label="数量调整"
        placeholder="点击选择"
        @click="quantityPicker = true"
      />
      <van-popup v-model="quantityPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          value-key="MoveTypeName"
          @confirm="quantityAdjustConfirm"
          @cancel="quantityPicker = false"
        />
      </van-popup>
      <van-field
        v-model="code"
        clearable
        label="拍码"
        ref="pmfocus"
        @focus="stopKeyborad"
        placeholder="请输入拍码"
      />
      <ag-grid-vue
        style="width: 100%; height: 55vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        :singleClickEdit="true"
        rowSelection="multiple"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <van-button block type="info" class="mt-1" @click="handleSubmit"
        >提交</van-button
      >
      <NumAdjust
        v-model="NumAdjustVsible"
        @adjustNum="adjustNum"
        @canCel="canCel"
        :Asure="sureAN"
        :ShowData="NumAdjustData"
        :AdjustStatue="this.selectedQuantity.AfterStatus"
      />
    </van-form>
  </div>
</template>

<script>
import { AgGridVue } from "ag-grid-vue";
import { CODE_LENGTH } from "../../config";
import { AgGrid } from "../../mixins/AgGrid";
import { pat, quantityAdjusts, numAdjustSubmit } from "../../api/material";
import { parseQRCode, toast } from "../../utils/common";
import { Picker } from "vant";
import { isEmpty } from "ramda";
import NumAdjust from "../../components/NumAdjust";

export default {
  name: "QuantityAdjustment",
  components: { AgGridVue, [Picker.name]: Picker, NumAdjust },
  mixins: [AgGrid],
  data() {
    return {
      index: "",
      code: "",
      savenum: "",
      sureWIP: "",
      sureAN: false,
      NumAdjustVsible: false,
      submitSure: true,
      quantityPicker: false,
      columnDefs: [
        { headerName: "物料号", field: "ProductId", width: 100 },
        { headerName: "物料名称", field: "Producer", width: 125 },
        {
          headerName: "调前数量",
          field: "StockQuantity",
          width: 80,
        },
        { headerName: "调后数量", field: "Number", width: 75 },
      ],
      rowData: [],
      columns: [],
      NumAdjustData: [], //传给数组的数据
      rowPallenNoNum: [],
      readyData: {},
      selectedQuantity: {},
    };
  },
  watch: {
    code(val) {
      if (isEmpty(this.selectedQuantity)) {
        toast("请选择状态调整");
      } else if (val.length > CODE_LENGTH) {
        let res = parseQRCode(val);
        if (res) {
          this.findPat(res.palletNo);
          this.$refs.pmfocus.focus();
        } else {
          toast("无法识别");
        }
      }
      this.code = "";
      this.NumAdjustData = [];
    },
  },
  methods: {
    // 消除获取焦点时自动弹出键盘
    stopKeyborad() {
      this.$refs.pmfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.pmfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    async findPat(palletNo) {
      if (!this.rowData.find((it) => it.UniqueId === palletNo)) {
        let res = await pat(
          this.$store.getters.productionLine,
          palletNo,
          "",
          this.$store.getters.WarehouseId
        );
        console.log(res);
        if (res && res.Status == 200) {
          if (res.Data.Inventorystatus === this.selectedQuantity.BeforeStatus) {
            //展示组件
            this.NumAdjustVsible = true;
            //将数据放到组件数组中
            this.NumAdjustData.push(res.Data);
            this.readyDat = JSON.parse(JSON.stringify(res.Data));
          } else {
            toast("所选数量调整的状态与库存物料状态不同");
          }
        } else {
          toast(res.Msg);
        }
      } else {
        toast("此拍已被录入");
      }
    },
    async handleSubmit() {
      if (this.rowData.length > 0) {
        let user = this.$store.getters.user;
        let productionline = this.$store.getters.productionLine;
        let MoveTypeId = this.columns[this.index].MoveTypeId;
        let MoveTypeName = this.columns[this.index].MoveTypeName;
        let WareHouseId = this.rowData[0].WareHouseId;
        let WareHouseName = this.rowData[0].WareHouseName;
        let OperatorType = this.rowData[0].OperatorType;
        let InventoryStatus = this.rowData[0].Inventorystatus;
        this.getPalletNoNum();
        let res = await numAdjustSubmit(
          user,
          productionline,
          MoveTypeId,
          MoveTypeName,
          WareHouseId,
          WareHouseName,
          OperatorType,
          InventoryStatus,
          this.rowPallenNoNum
        );
        if (res.Status == 200) {
          toast("提交已完成");
          this.submitSure = true;
          this.rowPallenNoNum.length = 0;
          this.rowData = [];
        } else {
          toast(res.Msg);
          this.submitSure = false;
        }
      } else {
        toast("数据为空");
      }
      this.$refs.pmfocus.focus();
    },
    //将表单里的数据归类
    getPalletNoNum() {
      if (this.submitSure) {
        let _that = this;
        this.gridApi.forEachNode((node) => {
          _that.rowPallenNoNum.push({
            UniqueId: node.data.UniqueId,
            ActSumBoxAfter: node.data.Number,
          });
        });
      }
    },
    quantityAdjustConfirm(val, index) {
      this.selectedQuantity = val;
      this.quantityPicker = false;
      this.index = index;
      this.rowData = [];
      this.$refs.pmfocus.focus();
    },
    async getQuantityAdjusts() {
      let res = await quantityAdjusts();
      console.log(res);
      if (res && res.Status == 200 && res.Data.length) {
        this.columns = res.Data;
        console.log(res);
      } else {
        toast("无法获取状态调整选项，请联系管理员");
      }
    },
    //调数据组件
    adjustNum(savevalue, sure) {
      this.savenum = savevalue;
      this.sureWIP = sure;
      if (this.sureWIP == true) {
        this.rowData.push(this.readyDat);
        this.sureWIP = "";
      }
      this.rowData[this.rowData.length - 1].Number = Number(this.savenum);
      this.gridApi.refreshCells();
      this.savenum = "";
      this.$refs.pmfocus.focus();
    },
    canCel(sure) {
      this.sureWIP = sure;
      this.NumAdjustVsible = false;
      this.savenum = "";
      this.$refs.pmfocus.focus();
    },
  },
  mounted() {
    this.getQuantityAdjusts();
    this.$refs.pmfocus.focus();
    document.onkeydown = function (e) {
      if (e.code == "Enter") {
        e.preventDefault();
      }
    };
  },
};
</script>
